package pdf

import entity.ReportData
import net.sf.jasperreports.engine.JasperCompileManager
import net.sf.jasperreports.engine.JasperFillManager
import net.sf.jasperreports.engine.JasperPrint
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource
import net.sf.jasperreports.engine.export.JRPdfExporter
import net.sf.jasperreports.export.SimpleExporterInput
import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput
import java.io.File

fun main() {
    // 模板文件的路径
    val baseTemplatePath = "src/main/resources/template/base.jrxml"
    val reportTemplatePath = "src/main/resources/template/report.jrxml"

    val data = listOf(ReportData())
    val pdfPath = File("D:/merged.pdf")

    // 设置参数的值
    val parameters = hashMapOf<String, Any>()
    parameters["result"] = "电机驱动端轴承损伤,轴承异常+不平衡"
    parameters["suggest"] =
        "预警内容：复查机组的平衡精度，进行动平衡校验。平衡精度满足GB/T9239.1-2006/ISO1940-1：2003《机械振动.恒态（刚性）转子平衡品质要求第1部分：规范与平衡允差的检验》中规定的G6.3级标准;检查轴承磨损情况和润滑情况，并检查轴承配合情况。检查的标准应满足GB/T 275-1993 《滚动轴承与轴和外壳的配合》的相关规定;"
    parameters["name"] = "离心液泵"
    val jasperPrint1 = fillJasperPrints(baseTemplatePath, parameters, data)
    val jasperPrint2 = fillJasperPrints(reportTemplatePath, parameters, data)

    val jasperPrints = listOf(jasperPrint1)

    mergeJasperPrintsToPdf(jasperPrints, pdfPath)
}

// 填充数据
fun fillJasperPrints(templatePath: String, hashMap: HashMap<String, Any>, data: List<ReportData>): JasperPrint {
    val jasperReport = JasperCompileManager.compileReport(templatePath)
    val dataSource = JRBeanCollectionDataSource(data)
    return JasperFillManager.fillReport(jasperReport, hashMap, dataSource)
}

fun mergeJasperPrintsToPdf(jasperPrints: List<JasperPrint>, outputFilePath: File) {
    runCatching {
        val exporter = JRPdfExporter()
        exporter.setExporterInput(SimpleExporterInput.getInstance(jasperPrints))
        exporter.setExporterOutput(SimpleOutputStreamExporterOutput(outputFilePath))
        exporter.exportReport()
        println("PDF文件已生成：${outputFilePath.path}")
    }.onFailure { e ->
        e.printStackTrace()
    }
}